package org.tc.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.tc.common.Result;
import org.tc.common.ResultUtils;
import org.tc.utils.JsonUtils;
import org.tc.utils.ResponseUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * Created by zxd on 2018/1/24.
 */
public class CustomerHandlerException implements HandlerExceptionResolver{

    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handle, Exception exception) {
        ModelAndView modelAndView=new ModelAndView();

        String msg;
        if(exception instanceof  CustomException){
            //如果是自定义异常获取异常信息
            msg=exception.getMessage();
        }else{
            //如果运行时异常
            exception.printStackTrace();
            msg="对不起，系统开小差了";
        }

        //判断返回就送数据还是跳转页面
        HandlerMethod handlerMethod= (HandlerMethod) handle;
        //调用的controller获取方法
        Method method = handlerMethod.getMethod();

        //1.判断处理器的方法上有没有responseBody注
        //2.判断返回的是不是 ResponseEntity 方法，如果是返回json

       //1.查找当前调用的controller上有没有responseBody注解
        ResponseBody annotation = AnnotationUtils.findAnnotation(method, ResponseBody.class);

        if(annotation!=null||ResponseEntity.class.getName().equals(method.getReturnType().getName())){
            //返回json数据
            Result result = ResultUtils.buildFail(500, msg);
            //转成json字符串返回给页面
            String json=JsonUtils.objectToJson(result);
            //响应给调用方
            ResponseUtils.responseJson(response,json);
            return modelAndView;
        }

        modelAndView.addObject("msg",msg);
        modelAndView.setViewName("error/exception");
        return modelAndView;
    }


}
